<!--  -->
<template>
<div class='backs'>
  <div class='backstage'>
    <div class="backstage_title">
      <div class="backstage_title_switch">
         <span class="backstage_mess">后台权限:</span>
         <i-switch size="large" v-model="isSwitch">
            <span slot="open">开启</span>
            <span slot="close">关闭</span>
         </i-switch>  
      </div>
      <div class="backstage_tabs">
          <span @click="changetabType('router')" :class="['backstage_tabs_left',tabType == 'router'?'active':''] ">菜单权限</span>
          <span @click="changetabType('button')" :class="['backstage_tabs_left',tabType != 'router'?'active':'']">按钮权限</span>
      </div>
    </div>
    <div class="backstage_boxList">
      <div v-if="tabType == 'router'" class="backstage_mainBox">
        <div v-for="(item,index) in currentList" :key="item.id" >
          <div v-if="item.permissionCode!='home'" :class="['backstage_boxs',item.pageUp?'active':'']">
            <!-- {{item}} -->
            <!-- 第一级-->
            <Icon type="ios-arrow-up" @click="pagesFold(item,index)" v-if="item.childPermission.length>0" class="backstage_boxs_firstUp" />
            <h2 ><Checkbox v-model="item.selected" @on-change="checkboxed(item,[index])" class="firstCheckbox"></Checkbox>{{item.permissionTitle}}</h2>  
            <div v-for="(it,itNum) in item.childPermission" :key="it.id" class="backstage_boxs_thirsBox">
              <!-- 第二级--> 
              <!-- <div v-if="it.backstageControl === '1'"> -->
                <h3 class="backstage_boxs_titleSecond"><Checkbox v-model="it.selected" @on-change="checkboxed(it,[index,itNum])" class="secondCheckbox"></Checkbox>{{it.permissionTitle}}</h3> 
                <!-- 第三级--> 
                <div v-for="(thirdMess,thirdMessNumber) in it.childPermission" :key="thirdMess.id" class="backstage_boxs_titleThreeBox">
                <div v-if="thirdMess.permissionType === '1002'  || thirdMess.backstageControl === '1' ">
                  <h3 class="backstage_boxs_titleThree"><Checkbox v-model="thirdMess.selected" @on-change="checkboxed(thirdMess,[index,itNum,thirdMessNumber])" class="secondCheckbox"></Checkbox>{{thirdMess.permissionTitle}}</h3> 
                  <!-- 第四级 -->
                  <Divider v-if="thirdMess.childPermission && !thirdMess.nochild && thirdMess.childPermission.length>0" :dashed="true" />
                  <!-- <div class="backstage_boxs_thirsBox_allselected" v-if="thirdMess.childPermission && thirdMess.childPermission.length>0">
                      <span class="backstage_boxs_thirsBox_allselectedMess">全选</span>
                      <Checkbox @on-change="checkboxAlled(thirdMess)"></Checkbox>
                  </div> -->
                  <span  v-for="(mess,messNumber) in thirdMess.childPermission" :key="mess.id">
                    <span class="backstage_boxs_spans" v-if="mess.backstageControl === '1'">
                      <Checkbox v-model="mess.selected" @on-change="checkboxed(mess,[index,itNum,thirdMessNumber,messNumber])"></Checkbox>
                      {{mess.permissionTitle}}
                    </span>
                  </span>           
                </div>
                </div>	
              <!-- </div> -->
            </div>
          </div>
        </div>
      </div>  
      <div v-if="tabType != 'router'" class="backstage_mainBox">
        <div v-for="(item,index) in routerListForButton" :key="item.id" :class="['backstage_boxs',item.pageUp?'active':'']">
          <!-- 第一级-->
          <Icon type="ios-arrow-up" @click="pagesFold(item,index)" v-if="item.childPermission.length>0" class="backstage_boxs_firstUp" />
          <h2 >{{item.permissionTitle}}</h2>  
          <!-- 第二级-->
          <div v-for="mess in item.childPermission" :key="mess.id" class="backstage_boxs_thirsBox">
              
              <h3 class="backstage_boxs_titleSecondButton"><Checkbox class="zBoxCC"  v-model="mess.selected" @on-change="checkboxed(mess)"></Checkbox>{{mess.permissionTitle}}</h3> 
              <div class="backstage_boxs_titleThreeButton">
                <span v-for="secondMess in mess.childPermission" :key="secondMess.id">
                  <span v-if="secondMess.permissionType == '1003'"  class="backstage_boxs_spans">
                      <Checkbox  v-model="secondMess.selected" @on-change="checkboxed(secondMess)"></Checkbox>
				             <span> {{secondMess.permissionTitle}}</span> 
                  </span>
			          </span>
              </div>
			    </div>		 
		    </div>
      </div> 
      <div class="backstage_footTabs">
           <span class="backstage_footTabs_sure" @click="summitMess">保存</span>
           <span class="backstage_footTabs_clear" @click="emptyAllSelected">清空</span>
      </div>
    </div>
  </div>
</div>
  
</template>

<script>
import {Divider,Panel,Collapse  } from "view-design";
import {getTreeList, getTreeUpdate, getRoleUpdate} from '@/api/system_center'
export default {
components: {Divider,Panel,Collapse},
data() {
 return {
  tabType:'router',
	routerListAfter:[],
	routerListAfter1:[],
  currentList:[],
	routerList:[],
  routerListForButton:[],
	single:"",
  isSwitch:true,
  noShowRouetrs:{},
 };
},
computed: {},
watch: {
  tabType(mess){
    this.boxAddAuto()
    this.boxAddHeight();
  }
},
created() {
  let {id, web} = this.$route.query;
  this.isSwitch = web == 1?true:false;
  this.web = web;
  this.id = id;
  this.getBackstage()
  
},
mounted() {
   this.changeList(this.routerList);
   this.currentList = this.routerList;
   
},
methods: {
 //获取后台权限类表
 getBackstage(mess={}){
	 let params = {roleId:this.id, clientType:1, permissionTypes:this.tabType == 'router'?[1001,1002]:[1001,1003]};
   params = Object.assign(params,mess);
   getTreeList(params).then(res=>{
  console.log("权限列表",res)
  if(this.tabType=="router"){
    this.routerListAfter =[]; 
    this.changeList(res);
    console.log('同级',this.noShowRouetrs);
    console.log('被选中的',this.routerListAfter)
    this.currentList =res
  }else{
    let arr = this.deleteNoParent(res);
    this.routerListAfter1 =[]; 
    console.log(1100,arr)
    this.changeList(arr);
    console.log(1111,this.routerListAfter1)
    this.routerListForButton =arr;
  }
  this.boxAddHeight();
  
   })
 },
 //按钮权限的时候  处理数据
  changetabType(name){
    this.tabType = name;
    console.log(888, this.tabType)
    if(name == 'button' && this.routerListForButton.length == 0)
    this.getBackstage()
      
  },
  checkboxed(item,indexArray,flag){
    let {selected ,id} = item,
    arr = this.tabType == 'router'?this.routerListAfter:this.routerListAfter1,
    index =arr.findIndex(item=>item == id),
    noShowIds = this.noShowRouetrs[id];
    console.log(id,arr)
    //if(noShowIds)this.noShowRouterChecked(id,noShowIds)
    selected && index<0 ? arr.push(id) : !selected && index>=0 ? arr.splice(index,1):"";
    //选中 下级都被选中
    item.childPermission && !flag &&this.selectedLower(item.childPermission,selected)
    //让上级选中
   indexArray && indexArray.length>1 && selected &&!flag && this.selectedSuperior(this.currentList,indexArray,0)
    //取消的时候判断  如果当前同级没有了  就要让父级也取消
   !selected && indexArray && indexArray.length>1 &&  !flag && this.cacleParentSelected(this.currentList,indexArray,indexArray.length)
  },
  //取消的时候判断  如果当前同级没有了  就要让父级也取消
  cacleParentSelected(mess,indexArray,index){
    let length = indexArray.length,currentParent,flag;
    for (let i = 0; i < indexArray.length; i++) {
      if(index>=0 && i>=index-1)break;
     currentParent = mess[indexArray[i]];
    }
    flag = currentParent.childPermission.some(item => item.selected);
    if(!flag){currentParent.selected = flag;this.checkboxed(currentParent,'',true);}
  },
  //选中的时候 如果有同级的不显示
  noShowRouterChecked(id,noShowIds){
    return;
    let arr = this.tabType == 'router'?this.routerListAfter:this.routerListAfter1;
    if(index<0 && selected)//选中 同时数组里面没有值
      { arr = arr.concat([id]).concat(noShowIds?noShowIds:[]);
       console.log(333,arr)}
    else if(!selected && index>=0){//取消 同时数组里面有值
       if(noShowIds)noShowIds.forEach(cid=>{
          let i = arr.indexOf(cid);
          i>-1 && arr.splice(i,1)
       })
        arr.splice(index,1)
    }
  },
  //循环 下级选中
  selectedLower(mess,selected){
    mess.map(item=>{
      item.selected = selected;
      this.checkboxed(item)
      //item.childPermission && this.selectedLower(item.childPermission)
    })
  },
  //循环 上级选中
  selectedSuperior(mess,arrayList,index){
    console.log(mess,index,arrayList,arrayList[index],mess[arrayList[index]])
    mess[arrayList[index]].selected = true;
    this.checkboxed(mess[arrayList[index]],'',true);
    if(index < arrayList.length-1 && mess[arrayList[index]].childPermission.length>0)this.selectedSuperior(mess[arrayList[index]].childPermission,arrayList,index+1)
  },
  //循环遍历删除没有按钮配置的父集
  deleteNoParent(messList){
    let mess = JSON.parse(JSON.stringify(messList));
    for (let index = mess.length-1; index >= 0; index--) {
       mess[index].noChildren = this.changeMess(mess[index].childPermission);
       console.log( mess[index], mess[index].noChildren)
       if(!mess[index].noChildren) mess.splice(index, 1);
    }
    return mess;
  },
  changeMess(arr){
    let flag = false;
    for (let index = 0; index < arr.length; index++) {
        if(arr[index].permissionType == '1003'){
          flag = true;
          return true;
        }
     arr[index].childPermission &&  (arr[index].noChildren = flag = this.changeMess(arr[index].childPermission))
    }
     return flag;  
  },
  //将selected的值转换成布尔值 并将选中的值放入一个新的数组 将某些路由不显示但是需要跟父级绑到一起（像 一些详情 添加页面）
   changeList(mess,parentMess){
      mess.map(item=>{
          let {selected, id, childPermission, permissionType, backstageControl} = item
          item.selected = selected == "true";
          selected == "true" && (this.tabType == 'router'?this.routerListAfter.push(id):(permissionType =='1003'?this.routerListAfter1.push(id):''));
          if(permissionType === '1001' && backstageControl === '0'){
            item.selected = parentMess.selected;
            !this.noShowRouetrs[parentMess.id] && (this.noShowRouetrs[parentMess.id]=[]);
            this.noShowRouetrs[parentMess.id].push(item.id)
          }
          if(childPermission && childPermission.length>0){
           let flag =  childPermission.some(it => it.backstageControl === '1');
           if(!flag)item.nochild = true;
           this.changeList(childPermission,item);
          }
      })
   },
   pagesFold(item,index){
     item.pageUp = item.pageUp?false:true;
     this.currentList.splice(index,1,item)
     console.log(this.routerList)
   },
   //清空所以选中的
   emptyAllSelected(){
    let arr =  this.tabType == 'router'?this.currentList:this.routerListForButton;
    this.recursiveArray(arr)
   },
   //递归循环
   recursiveArray(arr){
       arr.map(item=>{
         item.selected = false;
         item.childPermission && this.recursiveArray(item.childPermission)
       })
   },
   //全选
  checkboxAlled(mess){
    mess.ifAllselected = mess.ifAllselected?false:true;
    mess.childPermission.map(item=>{
        item.selected = mess.ifAllselected;
        this.checkboxed(item)
    })
  },
  //提交按钮
  summitMess(){
	  this.changeControl();
	  let permissionTypes = this.tabType == 'router'?[1001,1002]:[1003],
	  allPermissions = this.tabType == 'router'?this.routerListAfter:this.routerListAfter1;
	  getTreeUpdate({roleId:this.id, clientType:1, permissionTypes, allPermissions,}).then(res=>{
      this.$Message.success("修改成功")
	  	this.getBackstage()
	  })
  },
  //权限发生变化 掉接口
  changeControl(){
    let isSwitch = this.isSwitch?'1':'2',{id,app}=this.$route.query
    getRoleUpdate({loginWeb: isSwitch,roleId:this.id}).then(res=>{
    this.$Message.success("权限修改成功");
    this.$router.push({path:`/system_center/roleControl/roleControling`,query:{
      id,
      web:isSwitch,
      app,
    }})
	}).catch(err=>this.$Message.error("权限修改失败"))
  },
  //给每一个div添加高度
  boxAddHeight(){
    setTimeout(_=>{
       let doxs = document.querySelectorAll(".backstage_boxs");
      [...doxs].map(dox=>{
          dox.clientHeight>120 && (dox.style.height = dox.clientHeight+"px")
      })
    },1000)
    
  },
  //切换之前给每一个div的高度变成auto
  boxAddAuto(){
     let doxs = document.querySelectorAll(".backstage_boxs");
      [...doxs].map(dox=>{
          dox.style.height = 'auto'
      })
  }
},

}
</script>
<style lang='scss' scoped>
.backs{
    max-height: 100%;
    overflow-y: auto;
    height: 100%;
 .backstage{
    padding:0 24px;
    height: calc(100% - 3px);
    /deep/.ivu-divider-horizontal{
      margin: 12px 0;  
    }
    &_boxList{
      height: calc(100% - 47px);
      max-height: calc(100% - 47px);
      overflow-y: auto;  
    }
    &_mainBox{
     // max-height: calc(100% - 32px);
      min-height: calc(100% - 94px);
     // overflow-y: auto;  
    }
    &_mess{
        margin-right: 20px;
    }
    &_tabs{
      width: 260px;
      height: 32px;
      background: #f2f4f7;
      border-radius: 16px;
      color: #000;
      display: inline-block;
      &_left{
        width: 130px;
        height: 32px;
        display: inline-block;
        line-height: 32px;
        text-align: center;
        cursor: pointer;
      }
      &_left.active{
        background: #ffffff;
        border: 1px solid #2298ff;
        border-radius: 16px; 
        color: #0088FF;
        font-weight: 700; 
      }
    }
    &_title{
        text-align: center;
        margin-bottom: 15px;
        &_switch{
          float: left;  
        }
    }
    &_boxs.active{
      height: 60px!important;
      .backstage_boxs_firstUp{
        transform: rotate(180deg);  
      }
    }
    &_boxs{
      background: #ffffff;
      border-radius: 2px;
      box-shadow: 0px 0px 6px 0px rgba(38,42,45,0.08);  
      margin: 5px 0; 
      padding: 20px 0 20px 30px;
      position: relative;
      transition: all .5s;
      overflow: hidden;
      &_spans{
        display: inline-block;
        width: 140px;
        line-height: 24px;
        margin-bottom: 10px;
      }
      &_titleThreeButton{
        margin-left: 29px;
      }
      &_titleSecond{
       font-weight: 700;
	     margin: 12px 0 12px 24px;
	    }
      &_titleSecondButton{
       font-weight: 700;
	     margin: 12px 0 12px 15px;
       
	    }
	    &_titleThreeBox{
	      margin: 0 0 20px 46px;
	      	  position: relative;
   
	    }
     &_thirsBox{
       position: relative;
      //  display: flex;
      // flex-direction: row;
       &_allselected{
         position: absolute;
         right: 9px;
         top: 13px;
       }
       &_allselectedMess{
           margin-right: 4px;
       } 
     }
     &_firstUp{
        //color: #ccc; 
        position: absolute;
        right: 20px;
        top: 25px;
        cursor: pointer; 
        transform: rotate(0deg);
        transition: all .5s;
     }  
    }
    &_footTabs{
      margin-top: 14px;
      padding: 20px 0;
      text-align: center;
      background: #f0f2f5;
    //   width: 100%;
    //   bottom: 0;
    //   position: absolute;
      &_sure{
       width: 140px;
       height: 34px;
       background: #2298ff;
       border-radius: 2px;
       margin-right: 20px;
       color: #fff;
       text-align: center;
       line-height: 34px;
       display: inline-block;
       cursor: pointer;
      }
      &_clear{
        width: 120px;
        height: 34px;
        background: #ffffff;
        border: 1px solid rgba(0,0,0,0.1);
        border-radius: 2px;
        text-align: center;
        line-height: 34px;
        display: inline-block;
        cursor: pointer;

      }
    }
    .firstCheckbox{
       float: left;
       margin-top: 6px; 
    }
    .secondCheckbox{
       float: left;
    }
  }
}
.zBoxCC{
  margin-top: 12px;
}
  
</style>